package com.lry.basic.metrics;

import com.lry.basic.metrics.spi.EnhancedServiceLoader;

import java.io.IOException;

public class Main {
    //localhost:9898
    public static void main(String[] args) throws IOException, InterruptedException {

        Registry registry = EnhancedServiceLoader.load(Registry.class,"compact");

        Exporter exporter = EnhancedServiceLoader.load(Exporter.class,"prometheus");
        exporter.setRegistry(registry);


        EventBusManager.get().register(new MetricsSubscriber(registry));

        testCommit();

//        testRollback();

        System.in.read();
    }

    private static void testCommit(){
        new Thread(()->{
            int id = 1;
            while(true){
                long start = System.currentTimeMillis();
                //开启全局事务
                EventBusManager.get().post(new GlobalTransactionEvent(id,GlobalTransactionEvent.ROLE_TC,"tranName"+id,
                        start ,null,GlobalStatus.Begin));

                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //提交全局事务
                EventBusManager.get().post(new GlobalTransactionEvent(id,GlobalTransactionEvent.ROLE_TC,"tranName"+id,
                        start,System.currentTimeMillis(),GlobalStatus.Committed));
                id+=2;
            }
        }).start();
    }

    private static void testRollback(){
        new Thread(()->{
            int id = 2;
            while(true){
                long start = System.currentTimeMillis();
                //开启全局事务
                EventBusManager.get().post(new GlobalTransactionEvent(id,GlobalTransactionEvent.ROLE_TC,"tranName"+id,
                        start ,null,GlobalStatus.Begin));

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //提交全局事务
                EventBusManager.get().post(new GlobalTransactionEvent(id,GlobalTransactionEvent.ROLE_TC,"tranName"+id,
                        start,System.currentTimeMillis(),GlobalStatus.Rollbacked));
                id+=2;
            }
        }).start();
    }

}
